/*
 * $Id$
 */
package corejs;

import static corejs.Line.EOL;

/**
 *
 * @author myang
 */
public class LineReaderSource implements Source {

   public static final Line EOF_LINE = new Line(null) {
      @Override
      public char current() { return EOF; }
      @Override
      public char next() { return EOF; }
      @Override
      public char peek() { return EOF; }
      @Override
      public int lineNum() { return 0; }
      @Override
      public int col() { return 0; }
   };
   private LineReader _lr;
   private Line _line;

   public LineReaderSource(final LineReader lr) {
      _lr = lr;
      _line = lr.readLine();
   }

   @Override
   public int lineNum() {
      return _line.lineNum();
   }

   @Override
   public int col() {
      return _line.col();
   }

   @Override
   public char current() {
      return _line.current();
   }

   @Override
   public char prev() {
      return _line.prev();
   }

   @Override
   public char next() {
      return EOL == _line.current() ? nextLine(true).current() : _line.next();
   }

   @Override
   public char peek() {
      return EOL == _line.current() ? nextLine(false).current() : _line.peek();
   }

   private Line nextLine(final boolean move) {
      final Line ln = _lr.readLine();
      if (move) {
         _line = ln;
      }
      return ln;
   }

   public static void main(final String... args) {
      final LineReaderSource lrs =
        new LineReaderSource(new StringsReader("hello", "world", "!"));
      for (char c = lrs.next(); c != EOF; c = lrs.next()) {
         System.out.print(c);
      }
   }
}
